package com.example.singing.view;

import com.example.singing.manager.SystemConfigManager;
import com.example.singing.model.SystemConfig;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import com.example.singing.util.BackupManager;
import com.example.singing.util.SystemMonitor;
import com.example.singing.util.ThemeManager;
import javafx.animation.FadeTransition;
import javafx.animation.ScaleTransition;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.util.Duration;

import java.io.File;
import java.util.Optional;

/**
 * 高端系统设置界面
 * 包含多个功能模块：主题设置、评分配置、数据管理、安全设置、通知配置、高级功能等
 */
public class SettingsView {
    private VBox view;
    private SystemConfigManager configManager;
    private SystemConfig config;
    private User currentUser;
    private TabPane tabPane;
    
    public SettingsView(User currentUser) {
        this.currentUser = currentUser;
        this.configManager = new SystemConfigManager();
        this.config = configManager.getConfig();
        createView();
    }
    
    /**
     * 创建设置界面
     */
    private void createView() {
        // 创建主滚动容器
        ScrollPane mainScrollPane = new ScrollPane();
        mainScrollPane.setFitToWidth(true);
        mainScrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        mainScrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
        mainScrollPane.setStyle("-fx-background-color: #f5f5f5;");
        
        // 创建内容容器
        VBox contentContainer = new VBox(20);
        contentContainer.setPadding(new Insets(20));
        contentContainer.setStyle("-fx-background-color: #f5f5f5;");
        
        // 标题区域
        HBox titleBox = createTitleSection();
        contentContainer.getChildren().add(titleBox);
        
        // 创建选项卡面板
        tabPane = new TabPane();
        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
        tabPane.setStyle("-fx-background-color: white; -fx-background-radius: 10;");
        tabPane.setPrefHeight(600); // 设置固定高度确保滚动
        
        // 添加各个设置选项卡
        tabPane.getTabs().addAll(
            createThemeTab(),
            createScoringTab(),
            createDataManagementTab(),
            createSecurityTab(),
            createNotificationTab(),
            createAdvancedTab(),
            createSystemStatusTab(),
            createPerformanceMonitorTab()
        );
        
        contentContainer.getChildren().add(tabPane);
        
        // 底部操作按钮
        HBox buttonBox = createBottomButtons();
        contentContainer.getChildren().add(buttonBox);
        
        // 将内容容器放入滚动面板
        mainScrollPane.setContent(contentContainer);
        
        this.view = new VBox(mainScrollPane);
    }
    
    /**
     * 创建标题区域
     */
    private HBox createTitleSection() {
        HBox titleBox = new HBox(15);
        titleBox.setAlignment(Pos.CENTER_LEFT);
        titleBox.setPadding(new Insets(10, 0, 20, 0));
        
        // 设置图标
        Circle iconCircle = new Circle(25, Color.web("#673ab7"));
        Label iconLabel = new Label("⚙");
        iconLabel.setStyle("-fx-font-size: 20px; -fx-text-fill: white;");
        StackPane iconPane = new StackPane(iconCircle, iconLabel);
        
        // 标题和描述
        VBox titleText = new VBox(5);
        Label title = new Label("系统设置");
        title.setStyle("-fx-font-size: 28px; -fx-font-weight: bold; -fx-text-fill: #2c3e50;");
        
        Label subtitle = new Label("配置系统参数、主题、安全性和高级功能");
        subtitle.setStyle("-fx-font-size: 14px; -fx-text-fill: #7f8c8d;");
        
        titleText.getChildren().addAll(title, subtitle);
        
        // 系统信息
        VBox systemInfo = new VBox(5);
        systemInfo.setAlignment(Pos.CENTER_RIGHT);
        Label versionLabel = new Label("版本: " + config.getVersion());
        versionLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #95a5a6;");
        
        Label lastModifiedLabel = new Label("最后修改: " + config.getLastModified().toString().substring(0, 19));
        lastModifiedLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #95a5a6;");
        
        systemInfo.getChildren().addAll(versionLabel, lastModifiedLabel);
        
        titleBox.getChildren().addAll(iconPane, titleText, new Region(), systemInfo);
        HBox.setHgrow(titleBox.getChildren().get(2), Priority.ALWAYS);
        
        return titleBox;
    }
    
    /**
     * 创建主题设置选项卡
     */
    private Tab createThemeTab() {
        Tab tab = new Tab("🎨 主题设置");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 主题选择
        VBox themeSection = createSection("界面主题", "选择您喜欢的界面主题");
        HBox themeBox = new HBox(15);
        
        ToggleGroup themeGroup = new ToggleGroup();
        RadioButton lightTheme = new RadioButton("浅色主题");
        RadioButton darkTheme = new RadioButton("深色主题");
        RadioButton autoTheme = new RadioButton("自动切换");
        
        lightTheme.setToggleGroup(themeGroup);
        darkTheme.setToggleGroup(themeGroup);
        autoTheme.setToggleGroup(themeGroup);
        
        // 设置当前选择
        switch (config.getTheme()) {
            case "light": lightTheme.setSelected(true); break;
            case "dark": darkTheme.setSelected(true); break;
            case "auto": autoTheme.setSelected(true); break;
        }
        
        // 添加主题更改监听器
        themeGroup.selectedToggleProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal == lightTheme) {
                config.setTheme("light");
            } else if (newVal == darkTheme) {
                config.setTheme("dark");
            } else if (newVal == autoTheme) {
                config.setTheme("auto");
            }
            // 实时应用主题更改
            applyThemeChange();
        });
        
        themeBox.getChildren().addAll(lightTheme, darkTheme, autoTheme);
        themeSection.getChildren().add(themeBox);
        
        // 颜色设置
        VBox colorSection = createSection("颜色配置", "自定义系统主色调");
        GridPane colorGrid = new GridPane();
        colorGrid.setHgap(15);
        colorGrid.setVgap(10);
        
        // 主色调预览按钮
        Button primaryPreviewBtn = new Button("预览");
        primaryPreviewBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", config.getPrimaryColor()));
        primaryPreviewBtn.setPrefWidth(60);
        
        // 强调色预览按钮
        Button accentPreviewBtn = new Button("预览");
        accentPreviewBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", config.getAccentColor()));
        accentPreviewBtn.setPrefWidth(60);
        
        // 主色调
        Label primaryLabel = new Label("主色调:");
        ColorPicker primaryPicker = new ColorPicker(Color.web(config.getPrimaryColor()));
        primaryPicker.setOnAction(e -> {
            config.setPrimaryColor("#" + primaryPicker.getValue().toString().substring(2));
            // 实时应用主题更改
            applyThemeChange();
            // 更新预览按钮
            updatePreviewButton(primaryPreviewBtn, primaryPicker.getValue());
        });
        
        // 强调色
        Label accentLabel = new Label("强调色:");
        ColorPicker accentPicker = new ColorPicker(Color.web(config.getAccentColor()));
        accentPicker.setOnAction(e -> {
            config.setAccentColor("#" + accentPicker.getValue().toString().substring(2));
            // 实时应用主题更改
            applyThemeChange();
            // 更新预览按钮
            updatePreviewButton(accentPreviewBtn, accentPicker.getValue());
        });
        
        colorGrid.add(primaryLabel, 0, 0);
        colorGrid.add(primaryPicker, 1, 0);
        colorGrid.add(primaryPreviewBtn, 2, 0);
        colorGrid.add(accentLabel, 0, 1);
        colorGrid.add(accentPicker, 1, 1);
        colorGrid.add(accentPreviewBtn, 2, 1);
        
        colorSection.getChildren().add(colorGrid);
        
        // 动画设置
        VBox animationSection = createSection("动画效果", "控制界面动画和音效");
        VBox animationBox = new VBox(10);
        
        CheckBox enableAnimations = new CheckBox("启用界面动画");
        enableAnimations.setSelected(config.isEnableAnimations());
        enableAnimations.setOnAction(e -> config.setEnableAnimations(enableAnimations.isSelected()));
        
        CheckBox enableSoundEffects = new CheckBox("启用音效");
        enableSoundEffects.setSelected(config.isEnableSoundEffects());
        enableSoundEffects.setOnAction(e -> config.setEnableSoundEffects(enableSoundEffects.isSelected()));
        
        animationBox.getChildren().addAll(enableAnimations, enableSoundEffects);
        animationSection.getChildren().add(animationBox);
        
        // 添加测试按钮
        VBox testSection = createSection("主题测试", "测试主题更改效果");
        HBox testButtons = new HBox(15);
        
        Button testPrimaryBtn = new Button("测试主色调");
        testPrimaryBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", config.getPrimaryColor()));
        testPrimaryBtn.setOnAction(e -> {
            // 随机更改主色调进行测试
            String[] colors = {"#ff5722", "#2196f3", "#4caf50", "#ff9800", "#9c27b0", "#f44336"};
            String randomColor = colors[(int)(Math.random() * colors.length)];
            config.setPrimaryColor(randomColor);
            applyThemeChange();
            testPrimaryBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", randomColor));
        });
        
        Button testAccentBtn = new Button("测试强调色");
        testAccentBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", config.getAccentColor()));
        testAccentBtn.setOnAction(e -> {
            // 随机更改强调色进行测试
            String[] colors = {"#ff5722", "#2196f3", "#4caf50", "#ff9800", "#9c27b0", "#f44336"};
            String randomColor = colors[(int)(Math.random() * colors.length)];
            config.setAccentColor(randomColor);
            applyThemeChange();
            testAccentBtn.setStyle(String.format("-fx-background-color: %s; -fx-text-fill: white;", randomColor));
        });
        
        testButtons.getChildren().addAll(testPrimaryBtn, testAccentBtn);
        testSection.getChildren().add(testButtons);
        
        content.getChildren().addAll(themeSection, colorSection, animationSection, testSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建评分设置选项卡
     */
    private Tab createScoringTab() {
        Tab tab = new Tab("📊 评分配置");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 默认评委数量
        VBox judgeSection = createSection("评委配置", "设置默认评委数量和评分范围");
        GridPane judgeGrid = new GridPane();
        judgeGrid.setHgap(15);
        judgeGrid.setVgap(10);
        
        Label judgeCountLabel = new Label("默认评委数量:");
        Spinner<Integer> judgeCountSpinner = new Spinner<>(1, 20, config.getDefaultJudgeCount());
        judgeCountSpinner.setEditable(true);
        judgeCountSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setDefaultJudgeCount(newVal));
        
        Label minScoreLabel = new Label("最低分数:");
        Spinner<Double> minScoreSpinner = new Spinner<>(0.0, 100.0, config.getMinScore(), 0.1);
        minScoreSpinner.setEditable(true);
        minScoreSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setMinScore(newVal));
        
        Label maxScoreLabel = new Label("最高分数:");
        Spinner<Double> maxScoreSpinner = new Spinner<>(0.0, 100.0, config.getMaxScore(), 0.1);
        maxScoreSpinner.setEditable(true);
        maxScoreSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setMaxScore(newVal));
        
        judgeGrid.add(judgeCountLabel, 0, 0);
        judgeGrid.add(judgeCountSpinner, 1, 0);
        judgeGrid.add(minScoreLabel, 0, 1);
        judgeGrid.add(minScoreSpinner, 1, 1);
        judgeGrid.add(maxScoreLabel, 0, 2);
        judgeGrid.add(maxScoreSpinner, 1, 2);
        
        judgeSection.getChildren().add(judgeGrid);
        
        // 智能评分设置
        VBox smartScoringSection = createSection("智能评分", "配置智能评分算法和验证规则");
        VBox smartBox = new VBox(10);
        
        CheckBox enableSmartScoring = new CheckBox("启用智能评分算法");
        enableSmartScoring.setSelected(config.isEnableSmartScoring());
        enableSmartScoring.setOnAction(e -> config.setEnableSmartScoring(enableSmartScoring.isSelected()));
        
        CheckBox enableScoreValidation = new CheckBox("启用评分验证");
        enableScoreValidation.setSelected(config.isEnableScoreValidation());
        enableScoreValidation.setOnAction(e -> config.setEnableScoreValidation(enableScoreValidation.isSelected()));
        
        CheckBox showDetailedScores = new CheckBox("显示详细评分信息");
        showDetailedScores.setSelected(config.isShowDetailedScores());
        showDetailedScores.setOnAction(e -> config.setShowDetailedScores(showDetailedScores.isSelected()));
        
        smartBox.getChildren().addAll(enableSmartScoring, enableScoreValidation, showDetailedScores);
        smartScoringSection.getChildren().add(smartBox);
        
        content.getChildren().addAll(judgeSection, smartScoringSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建数据管理选项卡
     */
    private Tab createDataManagementTab() {
        Tab tab = new Tab("💾 数据管理");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 自动备份设置
        VBox backupSection = createSection("自动备份", "配置数据自动备份策略");
        GridPane backupGrid = new GridPane();
        backupGrid.setHgap(15);
        backupGrid.setVgap(10);
        
        CheckBox autoBackup = new CheckBox("启用自动备份");
        autoBackup.setSelected(config.isAutoBackup());
        autoBackup.setOnAction(e -> config.setAutoBackup(autoBackup.isSelected()));
        
        Label backupIntervalLabel = new Label("备份间隔(小时):");
        Spinner<Integer> backupIntervalSpinner = new Spinner<>(1, 168, config.getBackupInterval());
        backupIntervalSpinner.setEditable(true);
        backupIntervalSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setBackupInterval(newVal));
        
        Label maxBackupsLabel = new Label("最大备份文件数:");
        Spinner<Integer> maxBackupsSpinner = new Spinner<>(1, 50, config.getMaxBackupFiles());
        maxBackupsSpinner.setEditable(true);
        maxBackupsSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setMaxBackupFiles(newVal));
        
        backupGrid.add(autoBackup, 0, 0, 2, 1);
        backupGrid.add(backupIntervalLabel, 0, 1);
        backupGrid.add(backupIntervalSpinner, 1, 1);
        backupGrid.add(maxBackupsLabel, 0, 2);
        backupGrid.add(maxBackupsSpinner, 1, 2);
        
        backupSection.getChildren().add(backupGrid);
        
        // 数据压缩和加密
        VBox dataSecuritySection = createSection("数据安全", "配置数据压缩和加密选项");
        VBox securityBox = new VBox(10);
        
        CheckBox enableCompression = new CheckBox("启用数据压缩");
        enableCompression.setSelected(config.isEnableDataCompression());
        enableCompression.setOnAction(e -> config.setEnableDataCompression(enableCompression.isSelected()));
        
        CheckBox enableEncryption = new CheckBox("启用数据加密");
        enableEncryption.setSelected(config.isEnableDataEncryption());
        enableEncryption.setOnAction(e -> config.setEnableDataEncryption(enableEncryption.isSelected()));
        
        securityBox.getChildren().addAll(enableCompression, enableEncryption);
        dataSecuritySection.getChildren().add(securityBox);
        
        // 手动备份操作
        VBox manualBackupSection = createSection("手动备份", "立即创建数据备份");
        HBox backupButtons = new HBox(15);
        
        Button createBackupBtn = new Button("创建备份");
        createBackupBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        createBackupBtn.setOnAction(e -> createManualBackup());
        
        Button exportConfigBtn = new Button("导出配置");
        exportConfigBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white;");
        exportConfigBtn.setOnAction(e -> exportConfiguration());
        
        Button importConfigBtn = new Button("导入配置");
        importConfigBtn.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white;");
        importConfigBtn.setOnAction(e -> importConfiguration());
        
        backupButtons.getChildren().addAll(createBackupBtn, exportConfigBtn, importConfigBtn);
        manualBackupSection.getChildren().add(backupButtons);
        
        content.getChildren().addAll(backupSection, dataSecuritySection, manualBackupSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建安全设置选项卡
     */
    private Tab createSecurityTab() {
        Tab tab = new Tab("🔒 安全设置");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 密码策略
        VBox passwordSection = createSection("密码策略", "配置用户密码安全要求");
        GridPane passwordGrid = new GridPane();
        passwordGrid.setHgap(15);
        passwordGrid.setVgap(10);
        
        CheckBox requirePasswordChange = new CheckBox("要求定期更改密码");
        requirePasswordChange.setSelected(config.isRequirePasswordChange());
        requirePasswordChange.setOnAction(e -> config.setRequirePasswordChange(requirePasswordChange.isSelected()));
        
        Label minLengthLabel = new Label("最小密码长度:");
        Spinner<Integer> minLengthSpinner = new Spinner<>(4, 20, config.getPasswordMinLength());
        minLengthSpinner.setEditable(true);
        minLengthSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setPasswordMinLength(newVal));
        
        passwordGrid.add(requirePasswordChange, 0, 0, 2, 1);
        passwordGrid.add(minLengthLabel, 0, 1);
        passwordGrid.add(minLengthSpinner, 1, 1);
        
        passwordSection.getChildren().add(passwordGrid);
        
        // 会话管理
        VBox sessionSection = createSection("会话管理", "配置用户会话超时和日志记录");
        GridPane sessionGrid = new GridPane();
        sessionGrid.setHgap(15);
        sessionGrid.setVgap(10);
        
        Label timeoutLabel = new Label("会话超时(分钟):");
        Spinner<Integer> timeoutSpinner = new Spinner<>(5, 480, config.getSessionTimeout());
        timeoutSpinner.setEditable(true);
        timeoutSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setSessionTimeout(newVal));
        
        CheckBox enableLoginLogging = new CheckBox("启用登录日志");
        enableLoginLogging.setSelected(config.isEnableLoginLogging());
        enableLoginLogging.setOnAction(e -> config.setEnableLoginLogging(enableLoginLogging.isSelected()));
        
        CheckBox enableAuditTrail = new CheckBox("启用审计跟踪");
        enableAuditTrail.setSelected(config.isEnableAuditTrail());
        enableAuditTrail.setOnAction(e -> config.setEnableAuditTrail(enableAuditTrail.isSelected()));
        
        sessionGrid.add(timeoutLabel, 0, 0);
        sessionGrid.add(timeoutSpinner, 1, 0);
        sessionGrid.add(enableLoginLogging, 0, 1, 2, 1);
        sessionGrid.add(enableAuditTrail, 0, 2, 2, 1);
        
        sessionSection.getChildren().add(sessionGrid);
        
        content.getChildren().addAll(passwordSection, sessionSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建通知设置选项卡
     */
    private Tab createNotificationTab() {
        Tab tab = new Tab("📧 通知设置");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 系统通知
        VBox systemNotificationSection = createSection("系统通知", "配置系统内部通知");
        VBox systemBox = new VBox(10);
        
        CheckBox enableSystemNotifications = new CheckBox("启用系统通知");
        enableSystemNotifications.setSelected(config.isEnableSystemNotifications());
        enableSystemNotifications.setOnAction(e -> config.setEnableSystemNotifications(enableSystemNotifications.isSelected()));
        
        systemBox.getChildren().add(enableSystemNotifications);
        systemNotificationSection.getChildren().add(systemBox);
        
        // 邮件通知
        VBox emailSection = createSection("邮件通知", "配置邮件通知服务");
        GridPane emailGrid = new GridPane();
        emailGrid.setHgap(15);
        emailGrid.setVgap(10);
        
        CheckBox enableEmailNotifications = new CheckBox("启用邮件通知");
        enableEmailNotifications.setSelected(config.isEnableEmailNotifications());
        enableEmailNotifications.setOnAction(e -> config.setEnableEmailNotifications(enableEmailNotifications.isSelected()));
        
        Label smtpHostLabel = new Label("SMTP服务器:");
        TextField smtpHostField = new TextField(config.getEmailSmtpHost());
        smtpHostField.textProperty().addListener((obs, oldVal, newVal) -> 
            config.setEmailSmtpHost(newVal));
        
        Label smtpPortLabel = new Label("SMTP端口:");
        Spinner<Integer> smtpPortSpinner = new Spinner<>(1, 65535, config.getEmailSmtpPort());
        smtpPortSpinner.setEditable(true);
        smtpPortSpinner.valueProperty().addListener((obs, oldVal, newVal) -> 
            config.setEmailSmtpPort(newVal));
        
        Label emailUsernameLabel = new Label("邮箱用户名:");
        TextField emailUsernameField = new TextField(config.getEmailUsername());
        emailUsernameField.textProperty().addListener((obs, oldVal, newVal) -> 
            config.setEmailUsername(newVal));
        
        Label emailPasswordLabel = new Label("邮箱密码:");
        PasswordField emailPasswordField = new PasswordField();
        emailPasswordField.setText(config.getEmailPassword());
        emailPasswordField.textProperty().addListener((obs, oldVal, newVal) -> 
            config.setEmailPassword(newVal));
        
        emailGrid.add(enableEmailNotifications, 0, 0, 2, 1);
        emailGrid.add(smtpHostLabel, 0, 1);
        emailGrid.add(smtpHostField, 1, 1);
        emailGrid.add(smtpPortLabel, 0, 2);
        emailGrid.add(smtpPortSpinner, 1, 2);
        emailGrid.add(emailUsernameLabel, 0, 3);
        emailGrid.add(emailUsernameField, 1, 3);
        emailGrid.add(emailPasswordLabel, 0, 4);
        emailGrid.add(emailPasswordField, 1, 4);
        
        emailSection.getChildren().add(emailGrid);
        
        content.getChildren().addAll(systemNotificationSection, emailSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建高级功能选项卡
     */
    private Tab createAdvancedTab() {
        Tab tab = new Tab("🚀 高级功能");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // AI功能
        VBox aiSection = createSection("AI智能功能", "配置人工智能分析功能");
        VBox aiBox = new VBox(10);
        
        CheckBox enableAIAnalysis = new CheckBox("启用AI智能分析");
        enableAIAnalysis.setSelected(config.isEnableAIAnalysis());
        enableAIAnalysis.setOnAction(e -> config.setEnableAIAnalysis(enableAIAnalysis.isSelected()));
        
        aiBox.getChildren().add(enableAIAnalysis);
        aiSection.getChildren().add(aiBox);
        
        // 实时同步
        VBox syncSection = createSection("实时同步", "配置多设备实时数据同步");
        VBox syncBox = new VBox(10);
        
        CheckBox enableRealTimeSync = new CheckBox("启用实时同步");
        enableRealTimeSync.setSelected(config.isEnableRealTimeSync());
        enableRealTimeSync.setOnAction(e -> config.setEnableRealTimeSync(enableRealTimeSync.isSelected()));
        
        syncBox.getChildren().add(enableRealTimeSync);
        syncSection.getChildren().add(syncBox);
        
        // 云备份
        VBox cloudSection = createSection("云备份", "配置云端数据备份");
        GridPane cloudGrid = new GridPane();
        cloudGrid.setHgap(15);
        cloudGrid.setVgap(10);
        
        CheckBox enableCloudBackup = new CheckBox("启用云备份");
        enableCloudBackup.setSelected(config.isEnableCloudBackup());
        enableCloudBackup.setOnAction(e -> config.setEnableCloudBackup(enableCloudBackup.isSelected()));
        
        Label cloudProviderLabel = new Label("云服务提供商:");
        ComboBox<String> cloudProviderCombo = new ComboBox<>();
        cloudProviderCombo.getItems().addAll("无", "AWS", "Azure", "Google Cloud");
        cloudProviderCombo.setValue(config.getCloudProvider().equals("none") ? "无" : config.getCloudProvider());
        cloudProviderCombo.setOnAction(e -> {
            String selected = cloudProviderCombo.getValue();
            config.setCloudProvider(selected.equals("无") ? "none" : selected);
        });
        
        cloudGrid.add(enableCloudBackup, 0, 0, 2, 1);
        cloudGrid.add(cloudProviderLabel, 0, 1);
        cloudGrid.add(cloudProviderCombo, 1, 1);
        
        cloudSection.getChildren().add(cloudGrid);
        
        // 性能监控
        VBox performanceSection = createSection("性能监控", "配置系统性能监控");
        VBox performanceBox = new VBox(10);
        
        CheckBox enablePerformanceMonitoring = new CheckBox("启用性能监控");
        enablePerformanceMonitoring.setSelected(config.isEnablePerformanceMonitoring());
        enablePerformanceMonitoring.setOnAction(e -> config.setEnablePerformanceMonitoring(enablePerformanceMonitoring.isSelected()));
        
        performanceBox.getChildren().add(enablePerformanceMonitoring);
        performanceSection.getChildren().add(performanceBox);
        
        content.getChildren().addAll(aiSection, syncSection, cloudSection, performanceSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建系统状态选项卡
     */
    private Tab createSystemStatusTab() {
        Tab tab = new Tab("📈 系统状态");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 数据统计
        VBox dataStatsSection = createSection("数据统计", "系统数据概览");
        GridPane statsGrid = new GridPane();
        statsGrid.setHgap(20);
        statsGrid.setVgap(10);
        
        SystemConfigManager.SystemStatus status = configManager.getSystemStatus();
        
        Label usersCountLabel = new Label("用户数量:");
        Label usersCountValue = new Label(String.valueOf(status.usersCount));
        usersCountValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #2196f3;");
        
        Label teamsCountLabel = new Label("队伍数量:");
        Label teamsCountValue = new Label(String.valueOf(status.teamsCount));
        teamsCountValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #4caf50;");
        
        Label competitionsCountLabel = new Label("比赛数量:");
        Label competitionsCountValue = new Label(String.valueOf(status.competitionsCount));
        competitionsCountValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #ff9800;");
        
        Label scoresCountLabel = new Label("评分记录:");
        Label scoresCountValue = new Label(String.valueOf(status.scoresCount));
        scoresCountValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #9c27b0;");
        
        statsGrid.add(usersCountLabel, 0, 0);
        statsGrid.add(usersCountValue, 1, 0);
        statsGrid.add(teamsCountLabel, 0, 1);
        statsGrid.add(teamsCountValue, 1, 1);
        statsGrid.add(competitionsCountLabel, 0, 2);
        statsGrid.add(competitionsCountValue, 1, 2);
        statsGrid.add(scoresCountLabel, 0, 3);
        statsGrid.add(scoresCountValue, 1, 3);
        
        dataStatsSection.getChildren().add(statsGrid);
        
        // 存储空间
        VBox storageSection = createSection("存储空间", "磁盘使用情况");
        VBox storageBox = new VBox(10);
        
        ProgressBar storageProgress = new ProgressBar(status.getUsedSpacePercentage() / 100.0);
        storageProgress.setPrefWidth(300);
        storageProgress.setStyle("-fx-accent: #4caf50;");
        
        HBox storageInfo = new HBox(10);
        Label storageLabel = new Label(String.format("已使用: %s / %s (%.1f%%)", 
            status.getFormattedUsedSpace(), 
            status.getFormattedTotalSpace(), 
            status.getUsedSpacePercentage()));
        storageLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        storageInfo.getChildren().addAll(storageProgress, storageLabel);
        storageBox.getChildren().add(storageInfo);
        
        storageSection.getChildren().add(storageBox);
        
        // 备份信息
        VBox backupInfoSection = createSection("备份信息", "备份文件统计");
        GridPane backupInfoGrid = new GridPane();
        backupInfoGrid.setHgap(20);
        backupInfoGrid.setVgap(10);
        
        Label backupCountLabel = new Label("备份文件数:");
        Label backupCountValue = new Label(String.valueOf(status.backupCount));
        backupCountValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #2196f3;");
        
        Label uploadFilesLabel = new Label("上传文件数:");
        Label uploadFilesValue = new Label(String.valueOf(status.uploadFilesCount));
        uploadFilesValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #4caf50;");
        
        Label lastBackupLabel = new Label("最后备份:");
        Label lastBackupValue = new Label(status.lastBackup);
        lastBackupValue.setStyle("-fx-font-weight: bold; -fx-text-fill: #ff9800;");
        
        backupInfoGrid.add(backupCountLabel, 0, 0);
        backupInfoGrid.add(backupCountValue, 1, 0);
        backupInfoGrid.add(uploadFilesLabel, 0, 1);
        backupInfoGrid.add(uploadFilesValue, 1, 1);
        backupInfoGrid.add(lastBackupLabel, 0, 2);
        backupInfoGrid.add(lastBackupValue, 1, 2);
        
        backupInfoSection.getChildren().add(backupInfoGrid);
        
        // 系统日志
        VBox logsSection = createSection("系统日志", "最近的系统操作记录");
        VBox logsBox = new VBox(5);
        
        ListView<String> logsList = new ListView<>();
        logsList.setPrefHeight(150);
        logsList.getItems().addAll(config.getSystemLogs());
        
        Button refreshLogsBtn = new Button("刷新日志");
        refreshLogsBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white;");
        refreshLogsBtn.setOnAction(e -> {
            logsList.getItems().clear();
            logsList.getItems().addAll(config.getSystemLogs());
        });
        
        logsBox.getChildren().addAll(logsList, refreshLogsBtn);
        logsSection.getChildren().add(logsBox);
        
        content.getChildren().addAll(dataStatsSection, storageSection, backupInfoSection, logsSection);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 创建底部操作按钮
     */
    private HBox createBottomButtons() {
        HBox buttonBox = new HBox(15);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.setPadding(new Insets(20, 0, 0, 0));
        
        Button resetBtn = new Button("重置为默认");
        resetBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
        resetBtn.setOnAction(e -> resetToDefaults());
        
        Button saveBtn = new Button("保存设置");
        saveBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        saveBtn.setOnAction(e -> saveSettings());
        
        Button cancelBtn = new Button("取消");
        cancelBtn.setStyle("-fx-background-color: #9e9e9e; -fx-text-fill: white;");
        cancelBtn.setOnAction(e -> cancelChanges());
        
        buttonBox.getChildren().addAll(resetBtn, cancelBtn, saveBtn);
        
        return buttonBox;
    }
    
    /**
     * 创建设置分组
     */
    private VBox createSection(String title, String description) {
        VBox section = new VBox(10);
        section.setPadding(new Insets(15));
        section.setStyle("-fx-background-color: #fafafa; -fx-background-radius: 8; -fx-border-color: #e0e0e0; -fx-border-width: 1px; -fx-border-radius: 8;");
        
        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #2c3e50;");
        
        Label descLabel = new Label(description);
        descLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #7f8c8d;");
        
        section.getChildren().addAll(titleLabel, descLabel);
        
        return section;
    }
    
    /**
     * 创建手动备份
     */
    private void createManualBackup() {
        try {
            BackupManager backupManager = BackupManager.getInstance();
            String backupPath = backupManager.createFullBackup();
            if (backupPath != null) {
                AlertUtil.showInfoAlert("备份成功", "完整系统备份已创建: " + backupPath);
            } else {
                AlertUtil.showErrorAlert("备份失败", "创建备份时发生错误");
            }
        } catch (Exception e) {
            AlertUtil.showErrorAlert("备份失败", "创建备份时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 导出配置
     */
    private void exportConfiguration() {
        try {
            BackupManager backupManager = BackupManager.getInstance();
            String timestamp = java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String defaultFileName = "system_config_" + timestamp + ".dat";
            
            // 这里可以添加文件选择对话框
            String filePath = "exports/" + defaultFileName;
            if (configManager.exportConfig(filePath)) {
                AlertUtil.showInfoAlert("导出成功", "系统配置已导出到: " + filePath);
            } else {
                AlertUtil.showErrorAlert("导出失败", "导出配置时发生错误");
            }
        } catch (Exception e) {
            AlertUtil.showErrorAlert("导出失败", "导出配置时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 导入配置
     */
    private void importConfiguration() {
        try {
            // 显示确认对话框
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认导入");
            alert.setHeaderText("导入系统配置");
            alert.setContentText("确定要导入配置文件吗？这将覆盖当前的系统设置。");
            
            Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                // 这里可以添加文件选择对话框
                String filePath = "imports/system_config.dat";
                if (configManager.importConfig(filePath)) {
                    AlertUtil.showInfoAlert("导入成功", "系统配置已从文件导入");
                } else {
                    AlertUtil.showErrorAlert("导入失败", "导入配置时发生错误");
                }
            }
        } catch (Exception e) {
            AlertUtil.showErrorAlert("导入失败", "导入配置时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 重置为默认设置
     */
    private void resetToDefaults() {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认重置");
        alert.setHeaderText("重置系统设置");
        alert.setContentText("确定要将所有设置重置为默认值吗？此操作不可撤销。");
        
        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            config.resetToDefaults();
            config.addSystemLog("系统设置已重置为默认值");
            AlertUtil.showInfoAlert("重置成功", "系统设置已重置为默认值");
        }
    }
    
    /**
     * 保存设置
     */
    private void saveSettings() {
        if (configManager.saveConfig()) {
            config.addSystemLog("系统设置已保存");
            
            // 应用主题更改
            ThemeManager themeManager = ThemeManager.getInstance();
            themeManager.updateTheme(config.getTheme(), config.getPrimaryColor(), config.getAccentColor());
            
            AlertUtil.showInfoAlert("保存成功", "系统设置已保存，主题更改将在下次启动时生效");
        } else {
            AlertUtil.showErrorAlert("保存失败", "保存系统设置时发生错误");
        }
    }
    
    /**
     * 取消更改
     */
    private void cancelChanges() {
        // 重新加载配置
        config = configManager.getConfig();
        AlertUtil.showInfoAlert("已取消", "更改已取消，设置已恢复");
    }
    
    /**
     * 创建性能监控选项卡
     */
    private Tab createPerformanceMonitorTab() {
        Tab tab = new Tab("📊 性能监控");
        tab.setClosable(false);
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 性能监控面板
        SystemMonitor systemMonitor = SystemMonitor.getInstance();
        VBox performancePanel = systemMonitor.createPerformancePanel();
        
        // 监控控制按钮
        VBox controlSection = createSection("监控控制", "启动或停止系统性能监控");
        HBox controlButtons = new HBox(15);
        
        Button startMonitorBtn = new Button("启动监控");
        startMonitorBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        startMonitorBtn.setOnAction(e -> {
            systemMonitor.startMonitoring();
            AlertUtil.showInfoAlert("监控启动", "系统性能监控已启动，数据将每5秒更新一次");
        });
        
        Button stopMonitorBtn = new Button("停止监控");
        stopMonitorBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
        stopMonitorBtn.setOnAction(e -> {
            systemMonitor.stopMonitoring();
            AlertUtil.showInfoAlert("监控停止", "系统性能监控已停止");
        });
        
        Button refreshBtn = new Button("刷新数据");
        refreshBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white;");
        refreshBtn.setOnAction(e -> {
            // 手动更新性能数据
            systemMonitor.updatePerformanceMetrics();
            AlertUtil.showInfoAlert("数据刷新", "性能数据已手动刷新");
        });
        
        Button testBtn = new Button("测试监控");
        testBtn.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white;");
        testBtn.setOnAction(e -> {
            // 测试性能监控功能
            systemMonitor.updatePerformanceMetrics();
            SystemMonitor.PerformanceMetrics metrics = systemMonitor.getCurrentMetrics();
            String message = String.format("测试结果:\nCPU: %.1f%%\n内存: %.1f%%\n磁盘: %.1f%%\n活跃用户: %d\n总操作: %d",
                metrics.cpuUsage, metrics.memoryUsage, metrics.diskUsage, 
                metrics.activeUsers, metrics.totalOperations);
            AlertUtil.showInfoAlert("性能监控测试", message);
        });
        
        // 添加实时状态显示
        Label statusLabel = new Label("监控状态: 未启动");
        statusLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        // 启动定时器更新状态
        javafx.animation.Timeline statusTimer = new javafx.animation.Timeline(
            new javafx.animation.KeyFrame(javafx.util.Duration.seconds(1), event -> {
                if (systemMonitor.isMonitoring()) {
                    statusLabel.setText("监控状态: 运行中 (数据每5秒更新)");
                    statusLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #4caf50;");
                } else {
                    statusLabel.setText("监控状态: 已停止");
                    statusLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #f44336;");
                }
            })
        );
        statusTimer.setCycleCount(javafx.animation.Timeline.INDEFINITE);
        statusTimer.play();
        
        controlButtons.getChildren().addAll(startMonitorBtn, stopMonitorBtn, refreshBtn, testBtn);
        controlSection.getChildren().addAll(controlButtons, statusLabel);
        
        content.getChildren().addAll(controlSection, performancePanel);
        tab.setContent(content);
        
        return tab;
    }
    
    /**
     * 实时应用主题更改
     */
    private void applyThemeChange() {
        try {
            // 获取当前场景
            javafx.scene.Scene scene = view.getScene();
            if (scene != null) {
                ThemeManager themeManager = ThemeManager.getInstance();
                themeManager.applyTheme(scene);
                
                // 强制刷新所有组件
                Platform.runLater(() -> {
                    // 重新应用样式到所有节点
                    applyStylesToAllNodes(scene.getRoot());
                });
            }
        } catch (Exception e) {
            System.err.println("应用主题更改失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新预览按钮颜色
     */
    private void updatePreviewButton(Button button, Color color) {
        String colorHex = "#" + color.toString().substring(2);
        button.setStyle(String.format(
            "-fx-background-color: %s; " +
            "-fx-text-fill: white; " +
            "-fx-background-radius: 5px; " +
            "-fx-border-radius: 5px;",
            colorHex
        ));
    }
    
    /**
     * 递归应用样式到所有节点
     */
    private void applyStylesToAllNodes(javafx.scene.Node node) {
        if (node == null) return;
        
        // 根据节点类型应用特定样式
        if (node instanceof Button) {
            Button button = (Button) node;
            String primaryColor = config.getPrimaryColor();
            String accentColor = config.getAccentColor();
            
            // 只对特定类型的按钮应用样式
            if (button.getText().contains("保存") || button.getText().contains("确定") || 
                button.getText().contains("创建") || button.getText().contains("启动") ||
                button.getText().contains("停止") || button.getText().contains("刷新")) {
                button.setStyle(String.format(
                    "-fx-background-color: %s; " +
                    "-fx-text-fill: white; " +
                    "-fx-background-radius: 5px; " +
                    "-fx-border-radius: 5px;",
                    primaryColor
                ));
            }
        } else if (node instanceof TabPane) {
            TabPane tabPane = (TabPane) node;
            String accentColor = config.getAccentColor();
            String textColor = "dark".equals(config.getTheme()) ? "#ecf0f1" : "#2c3e50";
            
            // 应用样式到TabPane
            tabPane.setStyle(String.format(
                "-fx-background-color: white; " +
                "-fx-background-radius: 10;"
            ));
        } else if (node instanceof Label) {
            Label label = (Label) node;
            String textColor = "dark".equals(config.getTheme()) ? "#ecf0f1" : "#2c3e50";
            label.setStyle("-fx-text-fill: " + textColor + ";");
        }
        
        // 递归处理子节点
        if (node instanceof javafx.scene.Parent) {
            javafx.scene.Parent parent = (javafx.scene.Parent) node;
            for (javafx.scene.Node child : parent.getChildrenUnmodifiable()) {
                applyStylesToAllNodes(child);
            }
        }
    }
    
    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}
